//
//  HomeViewController.m
//  OnlyOne
//
//  Created by lanou on 16/5/4.
//  Copyright © 2016年 psf. All rights reserved.
//

#import "HomeViewController.h"
#import "HomeCollectionCell.h"
#import "HomeListModel.h"
#import "CollectionViewCellFactory.h"

@interface HomeViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, strong) NSMutableArray *dataArray;//数据数组

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UICollectionView *collection;

@end

@implementation HomeViewController

//懒加载
- (NSMutableArray *)dataArray {
    if (_dataArray == nil) {
        self.dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

//get请求数据方法
- (void)getURL:(NSString *)urlString parameter:(NSDictionary *)dic callBack:(void(^)(id data))callBack {
    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //返回主线程
        dispatch_sync(dispatch_get_main_queue(), ^{
            if (data) {
                callBack(data);
                
                
                
            } else {
                callBack(error);
            }
        });
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.collection reloadData];
        });

    }];
    [task resume];
}



//数据请求
- (void)getData {
    [self getURL:HomePage_URL parameter:@{} callBack:^(id data) {
        NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
       // NSLog(@"%@",dataDic);
        
        NSArray *array = dataDic[@"data"];
        for (NSDictionary *dic in array) {
            HomeListModel *model = [[HomeListModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.dataArray addObject:model];
           // NSLog(@"%@",self.dataArray);
        }
    }];
                              
                              
    
}

//创建collectionView
- (void)createCollectionView {
    
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        self.collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64, screenWidth, screenHeight - 64 - 44) collectionViewLayout:flowLayout];
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    flowLayout.minimumInteritemSpacing = 0;
    //self.collection.bounces = NO;
    
    
        flowLayout.itemSize = CGSizeMake(screenWidth, screenHeight - 64 - 44);
        self.collection.backgroundColor = [UIColor colorWithRed:arc4random() % 256 / 255.0 green:arc4random() % 256 / 255.0 blue:arc4random() % 256 / 255.0 alpha:1.0];
    
        
        self.collection.delegate = self;
        self.collection.dataSource = self;
    self.collection.pagingEnabled = YES;
    self.collection.contentOffset = CGPointMake(screenWidth, 0);
    
        
        //注册cell 标识符就是model类名
        [self.collection registerNib:[UINib nibWithNibName:@"HomeCollectionCell" bundle:nil] forCellWithReuseIdentifier:NSStringFromClass([HomeListModel class])];

    

    
        [self.view addSubview:self.collection];
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.title = @"ONE";
    [self getData];
    
    [self createCollectionView];
   
    
    
    
    
    
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"search"] style:(UIBarButtonItemStyleDone) target:self action:@selector(searchClick)];
    self.navigationItem.leftBarButtonItem = item;
    
    UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"login"] style:(UIBarButtonItemStyleDone) target:self action:@selector(loginClick)];
    self.navigationItem.rightBarButtonItem = item1;
}

#pragma mark-------collectionView 的代理方法---------
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    NSLog(@"%ld",self.dataArray.count);

    return self.dataArray.count;
   }

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    HomeListModel *model = self.dataArray[indexPath.row];
    NSLog( @"%@",model);
    BaseCollectionViewCell *cell = [CollectionViewCellFactory cellWithModelClass:[model class] collectionView:collectionView index:indexPath];
    
    [cell setDataWithModel:model];
    return cell;
}


- (void)setCollectionViewLayout:(UICollectionViewLayout *)layout animated:(BOOL)animated {
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
